package com.tjnu.baiyi.action;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.tjnu.baiyi.entity.TbFriend;
import com.tjnu.baiyi.entity.TbUser;

@Scope("prototype")
@Controller("addFriend")
public class AddFriend extends BaseAction {
	private static final long serialVersionUID = -6294684795306831037L;

	@Override
	public String execute() throws Exception {
		try {
			// 获取当前登录的用户信息
			TbUser currentUser = (TbUser) session.getAttribute("currentUser");
			// 获取要关注的用户Id
			String id = request.getParameter("id").toString();
			// 先判断是否已经关注过该好友
			boolean flag = tbFriendDao.validateFriendByCurrentId(
					Integer.parseInt(id), currentUser.getUserId());
			if (flag) {
				// 未关注过：进行关注
				System.out.println("AddFriend.execute() flag == true");
				TbUser friend = tbUserDao.findById(Integer.parseInt(id));
				TbFriend myFriend = new TbFriend();
				myFriend.setTbUserByUserId(currentUser);
				myFriend.setTbUserByFriendId(friend);
				tbFriendDao.save(myFriend);
				session.setAttribute("flag", 0);// 已经关注
			} else {
				// 关注过：
				System.out.println("AddFriend.execute() flag == false");
				tbFriendDao.delete(currentUser.getUserId(),
						Integer.parseInt(id));
				session.setAttribute("flag", 1);// 未关注
			}
			return SUCCESS;
		} catch (Exception e) {
			return ERROR;
		}
	}
}
